import { useEffect, useRef } from 'react';
import type { Message } from '../../types';
import { MessageItem } from './MessageItem';

interface MessageListProps {
  messages: Message[];
  currentUserId?: string;
  className?: string;
  onDeleteMessage?: (messageId: string) => void;
}

export function MessageList({ messages, currentUserId, className = '', onDeleteMessage }: MessageListProps) {
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  
  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };
  
  useEffect(() => {
    scrollToBottom();
  }, [messages]);
  
  // 判断是否显示头像（连续消息合并显示）
  const shouldShowAvatar = (message: Message, index: number) => {
    if (index === 0) return true;
    
    const prevMessage = messages[index - 1];
    if (!prevMessage || !message) return true;
    
    const timeDiff = message.timestamp?.getTime() - prevMessage.timestamp?.getTime();
    const isSameUser = prevMessage.userId === message.userId;
    
    // 如果是不同用户或者时间间隔超过5分钟，显示头像
    return !isSameUser || timeDiff > 5 * 60 * 1000;
  };
  
  if (messages.length === 0) {
    return (
      <div className={`flex-1 flex items-center justify-center ${className}`}>
        <div className="text-center text-gray-500">
          <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
            </svg>
          </div>
          <p className="text-lg font-medium mb-2">还没有消息</p>
          <p className="text-sm">发送第一条消息开始聊天吧！</p>
        </div>
      </div>
    );
  }
  
  return (
    <div
      ref={containerRef}
      className={`flex-1 overflow-y-auto px-4 py-4 space-y-2 ${className}`}
    >
      {messages.map((message, index) => {
        // 检查消息对象是否有效
        if (!message || !message.id) {
          console.warn('Invalid message at index:', index, message);
          return null;
        }
        
        const isOwn = currentUserId ? message.userId === currentUserId : false;
        const showAvatar = shouldShowAvatar(message, index);
        
        return (
          <MessageItem
            key={message.id}
            message={message}
            isOwn={isOwn}
            showAvatar={showAvatar}
            onDelete={onDeleteMessage}
          />
        );
      })}
      
      {/* 滚动锚点 */}
      <div ref={messagesEndRef} />
    </div>
  );
}